const validate = require("validate.js");
const path = require("path");
const multer = require("multer");
const enterpriseModel = require("../models/enterpriseModel");

/**
 * 验证数据
 * @param rule 规则
 * @param data 数据
 */
exports.validateFunc = async (rule, data) => {
  validate.validators.isEnterprise = async function (id) {
    const enterprise = await enterpriseModel.findOne({
      _id: id,
    });
    if (enterprise) {
      return;
    }
    return "企业不存在";
  };
  await validate.async(data, rule);
};

const filePath = path.resolve(__dirname, `../public/static/image`);
// 设置上传文件的引擎
const storage = multer.diskStorage({
  // 表示文件存储的路径
  destination: (req, file, cb) => {
    // 设置存储路径为public的static文件夹
    cb(null, filePath);
  },
  filename: (req, file, cb) => {
    // 获取后缀名
    const extname = path.extname(file.originalname);
    // 构建新的名字
    const newName =
      new Date().getTime() +
      "-" +
      Math.floor(Math.random() * 9000 + 1000) +
      extname;
    cb(null, newName);
  },
});

// 文件上传
exports.uploading = multer({
  dest: filePath,
  storage,
  limits: {
    fileSize: 1024 * 1024 * 50,
  },
});

/**
 * 分页查询工具
 * @param model 模型
 * @param queryCondition 查询条件
 * @param relevance 关联的模型
 * @param relevanceTwo
 */
exports.getDataByPage = async (
    model,
    queryCondition,
    relevance,
    relevanceTwo
) => {
    const pageObj = {
        current: Number(queryCondition.current || 1) ,
        pageSize: Number(queryCondition.pageSize || 10),
    };
    // 删除分页信息
    delete queryCondition.pageSize;
    delete queryCondition.current;
    // 数据总条数
    pageObj.count = await model.countDocuments(queryCondition);
    // 总页数
    pageObj.totalPage = Math.ceil(pageObj.count / pageObj.pageSize);
    pageObj.rows = await model
        .find(queryCondition)
        .populate(relevance || null)
        .populate(relevanceTwo || null)
        .skip((pageObj.current - 1) * pageObj.pageSize) // 设置跳过的数据条数
        .sort({onShelfDate: -1})
        .limit(pageObj.pageSize); // 查询条数
    return pageObj;
}
